import java.util.ArrayList;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Test20 {
    //读写锁类
    static class MyReadWriteLock{
        ArrayList<Integer> list = new ArrayList<>();
        int size = 0;
        ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
        //给写方法加写锁
        public void write() throws InterruptedException {
                reentrantReadWriteLock.writeLock().lock();
                System.out.println("正在写...");
                list.add(size);
                size++;
                System.out.println("写完毕...");
            Thread.sleep(2000);
                reentrantReadWriteLock.writeLock().unlock();
        }
        //给读方法加读锁
        public void read() throws InterruptedException {
                reentrantReadWriteLock.readLock().lock();
                System.out.println("正在读...");
                for (int s:list) {
                    System.out.print(s);
                }
                System.out.println();
            Thread.sleep(2000);
                System.out.println("读完毕...");
                reentrantReadWriteLock.readLock().unlock();
        }
    }
    public static void main(String[] args) {
        MyReadWriteLock myReadWriteLock = new MyReadWriteLock();
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    myReadWriteLock.write();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread2.start();
        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    myReadWriteLock.write();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread3.start();
            Thread thread1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        myReadWriteLock.read();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            thread1.start();
        Thread thread11 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    myReadWriteLock.read();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread11.start();
    }

}
